/*jslint vars: true, forin: true, sloppy: true */
/*global angular, DialogFactory, debug, DM, defaults, ocDialog, $DF */
ocDialog.provider('ocDialog', function () {
	// Getter/Setter for defaults.
	var config = this.config = function (item, value) {
		if (!defaults.hasOwnProperty(item)) {
			throw new Error(debug["#1101"]);
		}

		if (angular.isDefined(value)) {
			defaults[item] = value;
		}
		return defaults[item];
	};

	this.$get = ['$q', '$http', '$rootScope', '$compile', function ($q, $http, $rootScope, $compile) {

		$DF.getDialogInstance = function () {
			// It makes the application layout can not compile "oc-dialog"
			// directive directly by this way.
			return $compile(this.$dialogRaw)($rootScope.$new()).data('dialogInstance');
		};

		var exports = {
			getDialogInstanceByDialogFactoryName: function (DFName) {
				var deffered = $q.defer();

				// DF (D)ialog (F)actory.
				if (DM.factoryList[DFName]) {
					deffered.resolve(DM.factoryList[DFName].getDialogInstance());
				} else {
					var url = defaults.ROUTE_PATH + defaults.ROUTE_PREFIX +
						DFName + defaults.ROUTE_SUFFIX;

					$http.get(url).success(function (raw) {
						deffered.resolve((new DialogFactory(DFName, raw)).getDialogInstance());
					}).error(function () {
						deffered.reject('Can NOT found by url: ' + url + '.');
					});
				}

				// Give a Dialog Element to callback function.
				return deffered.promise;
			},
			queryDialogByElement: DM.queryDialogByElement,
			alert: function (setup, parentDI) {
				this.getNewDI('oc-alert').then(function (DI) {
					angular.extend(DI.$$scope, setup);
					DI.openDialogFrom(parentDI);
				});
			},
			file: function (setup, parentDI) {
				this.getNewDI('oc-file').then(function (DI) {
					angular.extend(DI.$$scope, setup);
					DI.openDialogFrom(parentDI);
				});
			}
		};

		// Alias.
		exports.getNewDI = exports.getDialogInstanceByDialogFactoryName;
		exports.queryDI = exports.queryDialogByElement;

		return exports;
	}];
});
